/*
 * SignonController.java
 *
 * Created on October 3, 2008, 3:25 AM
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */

package org.vacuela.publishmx.web.controllers;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;
import org.vacuela.publishmx.constant.Constants;
import org.vacuela.publishmx.context.ServiceContext;
import org.vacuela.publishmx.domains.User;
import org.vacuela.publishmx.services.AdminService;
import org.vacuela.publishmx.web.bean.UserSession;

/**
 *
 * @author nestor.carrasco
 */
public class SignonController extends PublishBasedController{
    private AdminService svcAdmin;
    
    public void setAdminService(AdminService admin){
        svcAdmin = admin;
    }

    public ModelAndView commandAction(HttpServletRequest request, 
                HttpServletResponse response, ServiceContext context) throws Exception {
                String username = request.getParameter("username");
		String password = request.getParameter("password");
		context.setAttribute("userId", username);
                context.setAttribute("password",password);
                this.svcAdmin.getUserByPassword(context);
                User user = (User)context.getAttribute("userDomain");
		if (user == null) {
			return new ModelAndView("error", "message", "Invalid username or password.  Signon failed.");
		}
		else {
			UserSession userSession = new UserSession(user);			
			request.getSession().setAttribute(Constants.USER_SESSION_DATA, userSession);
			String forwardAction = request.getParameter("forwardAction");
			if (forwardAction != null) {
				response.sendRedirect(forwardAction);
				return null;
			}
			else {
				return new ModelAndView("home");
			}
		}
    }
    
}
